﻿using System;
using System.Data;
using DevControlLibrary.Common;
using DevExpress.Xpf.Editors.Settings;
using QueryResource.Common;
using QueryResource.ViewModel;
using System.Windows;
using DBAccessLibrary;
using System.Linq;
using DBAccessLibrary.Model;

namespace DevControlLibrary.UI
{
    /// <summary>
    /// GridViewControl.xaml 的交互逻辑
    /// </summary>
    [System.ComponentModel.DesignTimeVisible(false)]
    public partial class GridViewControl
    {
        public GridViewControl()
        {
            InitializeComponent();
           
            this.busyCtrl.Cancel += new EventHandler(busyCtrl_Cancel);
            this.gridControl1.KeyDown += new System.Windows.Input.KeyEventHandler(gridControl1_KeyDown);

            this.AllowDrop = true;
            this.DragOver += gridControl1_DragEnter;
            this.Drop += gridControl1_Drop;
            Init();

        }

       
        public GridViewModel ViewModel { get; set; }
        private void Init()
        {

            ViewModel = new GridViewModel() { 
                IsLoadPage = () => XmlHelper.Instance.IsPageBind, 
                LoadMaxCount = () => XmlHelper.Instance.SelectMaxCount, 
                ControlInvoke = act => this.InvokeEx(act), 
                GridCanelEdit = GridCanelEdit, 
                GridStartEdit = GridStartEdit, LoadDataSucess = WriteDataSucess, 
                GridCommitEdit = GridCommitEdit, 
                GridBind = GridControlBind,
                GridClear = GridControlClear };
            DataContext = this;
            this.busyCtrl.CanelButton = true;
            this.tableView1.ShowAutoFilterRow = XmlHelper.Instance.IsShowAutoFilterRow;
           
        }


        void busyCtrl_Cancel(object sender, EventArgs e)
        {
            this.ViewModel.LoadCanel();
        }
      
        #region 外界通信
       
        public Action<GridViewControl> AppendDataSucess { get; set; }
        /// <summary>
        /// 数据加载成功后 用于通知界面激活当前窗口
        /// </summary>
        private void WriteDataSucess()
        {
            if (AppendDataSucess != null)
            {
                AppendDataSucess(this);
            }
        }
      
        #endregion

        public void DataBind(string sql)
        {
            ViewModel.LoadData(sql);
        }
        public void RegistShowAutoFilterAction()
        {
            XmlHelper.Instance.ShowAutoFilterRowAction = flag => this.tableView1.ShowAutoFilterRow = flag;
        }
        public void Dispose()
        {
            AppendDataSucess = null;
            ViewModel.UnRegister();
        }
      
        void gridControl1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (btnSave.IsVisible && btnSave.Content.ToString() == "提交修改")
            {
                if (e.Key == System.Windows.Input.Key.Delete)
                {
                    DataRowView row = this.gridControl1.GetRow(this.tableView1.FocusedRowHandle) as DataRowView;
                    if (row == null)
                        return;
                    if (MessageBoxHelper.ShowMessage("是否确定要删除此行?", "提示", System.Windows.MessageBoxButton.OKCancel, System.Windows.MessageBoxImage.Question) == System.Windows.MessageBoxResult.OK)
                    {
                        ViewModel.RemoveRow(row.Row);
                        this.gridControl1.RefreshData();
                    }
                }
            }
        }

        private void GridControlBind(DataTable dt)
        {
            if (dt != null)
            {
                TableEntity table = null;
                if (ViewModel.IsAllowEdit && !string.IsNullOrEmpty(ViewModel.EditTableName))
                {
                    //如果是编辑状态 ，说明 是单表查询  将 列 转换成 英文[中文]
                    table = SysCache.TableList.FirstOrDefault(o => o.Name.Equals(ViewModel.EditTableName, StringComparison.CurrentCultureIgnoreCase));

                }
                foreach (DataColumn column in dt.Columns)
                {
                    string title = column.ColumnName;
                    if (table != null)
                    {
                        FieldEntity entity = table.FileNodes.FirstOrDefault(o => o.TransName == column.ColumnName);
                        if (entity != null)
                        {
                            if (!string.IsNullOrEmpty(entity.TransChName))
                            {
                                title = string.Format("{0}{1}{2}", entity.TransName,Environment.NewLine,entity.TransChName);
                            }
                        }
                    }
                    DevExpress.Xpf.Grid.GridColumn gc = new DevExpress.Xpf.Grid.GridColumn
                    {
                        FieldName = column.ColumnName,
                        Header = title,
                        ReadOnly = true
                    };
                   
                    if (column.ColumnName == "ROWNUMBER")
                        gc.Visible = false;
                    if (column.DataType == typeof(DateTime))
                    {
                        gc.EditSettings = new TextEditSettings
                        {
                            DisplayFormat = "yyyy-MM-dd HH:mm:ss.ffffff"
                        };
                        
                    }
                    if (column.DataType.IsGenericType)
                    {
                        gc.EditSettings = new TextEditSettings();
                    }
                   
                    this.gridControl1.Columns.Add(gc);
                }
            }

            this.gridControl1.FilterString = string.Empty;
            this.gridControl1.ItemsSource = dt;
            this.ViewModel.ExceptToExcelCommand.RaiseCanExecuteChanged();
            this.ViewModel.ExceptToSqlCommand.RaiseCanExecuteChanged();
        }
        private void GridControlClear()
        {
            this.gridControl1.Columns.Clear();
            this.gridControl1.ItemsSource = null;
        }
        private void GridCanelEdit()
        {
            this.tableView1.NewItemRowPosition = DevExpress.Xpf.Grid.NewItemRowPosition.None;
        }
        private void GridStartEdit()
        {
            this.tableView1.NewItemRowPosition = DevExpress.Xpf.Grid.NewItemRowPosition.Top;
            foreach (DevExpress.Xpf.Grid.GridColumn column in this.gridControl1.Columns)
            {
                column.ReadOnly = false;
            }
        }
        private void GridCommitEdit()
        {
            this.tableView1.CommitEditing();
        }

        #region 拖拽
        void gridControl1_DragEnter(object sender, DragEventArgs e)
        {
            //if (!e.Data.GetDataPresent(typeof(string)))
            //{
            //    e.Effects = DragDropEffects.None;
            //    e.Handled = true;
            //}
            bool isError = true;
            if (e.Data.GetDataPresent(typeof(string)))
            {
                string text = e.Data.GetData(typeof(string)).ToString();
                if (SysCache.TableList != null)
                {
                    if (SysCache.TableList.FirstOrDefault(o => o.TransName == text) != null ||
                        SysCache.ViewList.FirstOrDefault(o => o.TransName == text) != null)
                    {
                        isError = false;
                    }
                }
            }
            if (isError)
            {
                e.Effects = DragDropEffects.None;
                e.Handled = true;
            }
        }


        void gridControl1_Drop(object sender, System.Windows.DragEventArgs e)
        {
            if (e.Effects == DragDropEffects.None)
                return;

            if (e.Data.GetDataPresent(typeof(string)))
            {
                string text = e.Data.GetData(typeof(string)).ToString();
                DataBind("SELECT * FROM " + text);
            }
        }
        #endregion
    }

   
}
